<template>
  <el-cascader :props="props" v-model="selected" :clearable="clearable" placeholder="请选择" :style="{width: width}" @change="handleChange"></el-cascader>
</template>

<script>
import {listAreaByParId} from "@/api/system/area";

// 解决卡死问题
const observer = new MutationObserver(function(mutations, observer) {
  mutations.forEach(function(mutation) {
    mutation.addedNodes.forEach(node => {
      if (node.nodeType === 1) {
        const $el = node.querySelectorAll('.el-cascader-panel .el-cascader-node[aria-owns]'); Array.from($el).map(item => item.removeAttribute('aria-owns'))
      }
    })
  })
})
observer.observe(document.body, {
  characterData: false,
  childList: true,
  attributes: false,
  subtree: true
})

export default {
  name: "AreaCascader",
  model: {
    prop: "value",
    event: "update"
  },
  props: {
    width: {
      type: String,
      default: '100%'
    },
    parentId: String,
    value: String,
    onchange: Function,
    clearable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      props: {
        checkStrictly: true,
        emitPath: true,
        lazy: true,
        lazyLoad: this.lazyLoad
      }
    }
  },
  computed: {
    selected: {
      get() {
        if (this.value) {
          return this.value.split(',')
        }else {
          return []
        }
      },
      set(newV) {
        this.$emit('update', newV.join(','))
      }
    }
  },
  methods: {
    handleChange(nodes) {
      if (this.onchange) {
        this.onchange()
      }
    },
    lazyLoad (node, resolve) {
      const { root, value, hasChildren } = node;
      if (root === true) {
        listAreaByParId(this.parentId? this.parentId:"-1").then(res=> {
          const nodes = res.data.map(d=> {
            return {value: d.id, label: d.name, leaf: d.remark==='Town',...d}
          })
          resolve(nodes)
        });
      }else {
        if (hasChildren) {
          listAreaByParId(value).then(res=> {
            const nodes = res.data.map(d=> {
              return {value: d.id, label: d.name, leaf: d.remark==='Town',...d}
            })
            resolve(nodes)
          });
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
